﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Zws.Common;

namespace Zws.Frameworker.Filter
{
    public class ApiResultFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result is not EmptyResult)
            {
                if (context.Result is ObjectResult obj)
                {
                    //用自定义的ApiResult将返回结果包裹起来
                    context.Result = new JsonResult(new ApiResult<object>(StatusCode.SUCCESS, obj.Value!));
                }
                await next();
            }
            else
            {
                context.Cancel = true;
            }
        }
    }
}
